﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameViewer.Core.Archives
{
    public class FileSystemArchive : Archive
    {
        public FileSystemArchive(string name, string archType)
            : base(name, archType)
        {
        }

        public override void Load()
        {
            if (mName.EndsWith("\\") == false)
            {
                mName = mName + "\\";
            }
            this.Load(mName);
            //throw new NotImplementedException();
        }

        private void Load(string path)
        {
            string[] files = System.IO.Directory.GetFiles(path);
            foreach (string file in files)
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(file);

                FileInfo info = new FileInfo();
                info.Archive = this;
                info.BaseName = fi.Name;
                info.CompressedSize = fi.Length;
                info.FileName = fi.FullName.Replace(mName, "");
                info.Path = (fi.DirectoryName + "\\").Replace(mName, "");
                info.UnCompressedSize = info.CompressedSize;
                mFiles.Add(info);
            }

            string[] dirs = System.IO.Directory.GetDirectories(path);
            foreach (string dir in dirs)
            {
                this.Load(dir);
            }
        }

        public override System.IO.Stream Open(string fileName)
        {
            //throw new NotImplementedException();
            System.IO.Stream stream = System.IO.File.Open(System.IO.Path.Combine(mName, fileName), System.IO.FileMode.Open);
            System.IO.BinaryReader br = new System.IO.BinaryReader(stream);            
            System.IO.MemoryStream ms = new System.IO.MemoryStream(br.ReadBytes((int)stream.Length));
            ms.Position = 0;
            br.Close();
            stream.Close();
            return ms;
        }
    }

    public class FileSystemArchiveFactory : ArchiveFactory
    {
        public override string Type
        {
            get { return "FileSystem"; }
        }

        public override Archive CreateInstance(string name)
        {
            return new FileSystemArchive(name, "FileSystem");
        }
    }
}
